﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
// thread
using System.Threading;
// json
using Newtonsoft.Json;
// log4net
using log4net;
using log4net.Config;

using mesRUpload.UploadDataWebservice;


namespace mesRUpload
{
    public partial class MESUpload : Form
    {
        private string iniPath = AppDomain.CurrentDomain.BaseDirectory
                + "MesRUpload_Machine.ini";

        public static readonly ILog logger = LogManager.GetLogger("MesRUplodLogger"); // 重传日志
        public static readonly ILog consoleLogger = LogManager.GetLogger("DebugLogger"); // 控制台调试日志
        public static readonly ILog smtpLogger = LogManager.GetLogger("SmtpLogger"); // smtp 邮箱日志
        public static readonly ILog mifindLogger = LogManager.GetLogger("MiFindLogger"); // sfc 生成日志
        public static readonly ILog errorLogger = LogManager.GetLogger("ErrorLogger");
        public static readonly ILog infoLogger = LogManager.GetLogger("InfoLogger");
        //public static Logger log;

        public static string m_CCode = string.Empty; // 电芯码 虚拟码 公共信息
        public static string m_VCode = string.Empty;
        public static bool m_b_sfcIsNull = true;

        private delegate void SetPos(); // 代理
        private static object o = new object(); // 线程锁
        public static Thread t_loadFile; //, t_loadFilebar;
        public static bool t_isInLoadFile = false;

        public BackgroundWorker worker;

        private CSVInfo csvinfo; // 表格类
        const int TITLE = 1, NAME = 2, VALUE = 3, DATATYPE = 4;
        private ListViewItem m_listViewItem; // 列表视图
        private ListViewItem.ListViewSubItem m_listViewSubItem;
        private static string pwdKey = "mesrupload"; // 秘钥
        public static bool m_b_isOpen = false; // 密码查看

        private sfcDcExRequest m_sfcDcRequest; // DC 虚拟码获取响应请求
        private MiConnRequest m_MiConnRequest; // 电芯码获取响应请求
        private MachineConnRequest m_MachineConnRequest; // 上传连接与响应封装

        private List<machineIntegrationParametricData> m_parametricDataArray; // 上传请求数组
        private List<nonConfirmCodeArray> m_nonConfirmCodeArray;

        private int code = -1; // 响应回传
        private string message = string.Empty;

        public static MESUpload form1;
        public MESUpload()
        {
            InitializeComponent();
            form1 = this;

            G1_TB_sfc.Text = "未查询到 sfc";
            M_G2_CB_modeProcessSFC.SelectedIndex = 0;
            M_G1_TB_password.PasswordChar = '●';
            M_G1_PB_closeOpen.SizeMode = PictureBoxSizeMode.Zoom;

            initParams();
            initListCtrls(false, 0);
            initIni();

            csvinfo = CSVInfo.getinstance();
            csvinfo.init();

            infoLogger.Info("应用启动正常！");
            //Logger(LoggerName.MesRUplodLogger);

        }

        public void DoSearchSFC(bool b, bool isException = false)
        {
            t_isInLoadFile = !b;

            if (isException)
            {
                try
                {
                    t_loadFile.Abort();
                }
                catch (Exception e)
                {
                    MessageBox.Show(Timing.exceptionMess(e));
                    errorLogger.Error(Timing.exceptionMess(e));
                }
                finally
                {
                    t_loadFile = null;
                }
            }
            else
            {
            }
        }

        /// <summary>
        /// 初始化 webservice 连接与请求设置
        /// </summary>
        private void initParams()
        {
            m_MiConnRequest = new MiConnRequest();
            m_MachineConnRequest = new MachineConnRequest();

            m_sfcDcRequest = new sfcDcExRequest();
            m_sfcDcRequest.site = string.Empty;
            m_sfcDcRequest.user = string.Empty;
            m_sfcDcRequest.operation = string.Empty;
            m_sfcDcRequest.operationRevision = string.Empty;
            m_sfcDcRequest.activityId = string.Empty;
            m_sfcDcRequest.resource = string.Empty;
            m_sfcDcRequest.dcGroup = string.Empty;
            m_sfcDcRequest.dcGroupRevision = string.Empty;
            m_sfcDcRequest.modeProcessSfc = ModeProcessSfc.MODE_NONE;
            m_sfcDcRequest.sfc = string.Empty;
        }

        private void initIni()
        {
            if (!INIConfigAPI.InitPath(iniPath))
            {
                return;
            }

            initCtrlsText();
        }

        public void initCtrlsText()
        {
            //G1_TB_filepath.Text = INIConfigAPI.ReadFile(
            //    INIConfigAPI.file_id.directory);

            M_G1_TB_wsdl.Text = INIConfigAPI.ReadWebservice(
                INIConfigAPI.webservice_id.MESWSDL);
            M_G1_TB_timeout.Text = INIConfigAPI.ReadWebservice(
                INIConfigAPI.webservice_id.TimeOut);
            M_G1_TB_user.Text = INIConfigAPI.ReadWebservice(
                INIConfigAPI.webservice_id.User);
            M_G1_TB_password.Text = EnDecryptAPI.DeCrypt(INIConfigAPI.ReadWebservice(
                INIConfigAPI.webservice_id.Password), pwdKey);

            M_G2_TB_site.Text = INIConfigAPI.ReadRequest(
                INIConfigAPI.request_id.site);
            M_G2_TB_activityID.Text = INIConfigAPI.ReadRequest(
                INIConfigAPI.request_id.activityId);
            M_G2_TB_operation.Text = INIConfigAPI.ReadRequest(
                INIConfigAPI.request_id.operation);
            M_G2_TB_operationRevision.Text = INIConfigAPI.ReadRequest(
                INIConfigAPI.request_id.operationRevision);
            M_G2_TB_resource.Text = INIConfigAPI.ReadRequest(
                INIConfigAPI.request_id.resource);
            M_G2_TB_operationUser.Text = INIConfigAPI.ReadRequest(
                INIConfigAPI.request_id.user);
            M_G2_TB_dcGroup.Text = INIConfigAPI.ReadRequest(
                INIConfigAPI.request_id.dcGroup);
            M_G2_TB_dcGroupRevision.Text = INIConfigAPI.ReadRequest(
                INIConfigAPI.request_id.dcGroupRevision);
            switch (INIConfigAPI.ReadRequest(INIConfigAPI.request_id.modeProcessSfc))
            {
                case "COMPLETE_SFC":
                    M_G2_CB_modeProcessSFC.SelectedIndex = 2;
                    break;
                case "PASS_SFC":
                    M_G2_CB_modeProcessSFC.SelectedIndex = 3;
                    break;
                case "START_SFC":
                    M_G2_CB_modeProcessSFC.SelectedIndex = 1;
                    break;
                case "START_COMPLETE_SFC":
                    M_G2_CB_modeProcessSFC.SelectedIndex = 4;
                    break;
                case "NONE":
                default:
                    M_G2_CB_modeProcessSFC.SelectedIndex = 0;
                    break;
            }

            string parametricDataArray = INIConfigAPI.ReadWebservice(
                INIConfigAPI.webservice_id.MESWSDL);

            StringBuilder sb = new StringBuilder();
            sb = INIConfigAPI.ReadArray();

            string parametricDataArray1 = INIConfigAPI.ReadRequest(
                INIConfigAPI.request_id.parametricDataArray);
            try
            {
                if (parametricDataArray1 != "")
                {
                    Root rt = JsonConvert.DeserializeObject<Root>(parametricDataArray1);
                    for (int i = 0; i < rt.parametricDataArray.Count; i++)
                    {
                        string namei = rt.parametricDataArray[i].name;
                        string valuei = rt.parametricDataArray[i].value;
                        string datatypei = rt.parametricDataArray[i].dataType;
                        insertList(namei, valuei, datatypei);
                    }
                }
            }
            catch (Exception e) // json 解析异常
            {
                MessageBox.Show(Timing.exceptionMess(e));
                errorLogger.Error(Timing.exceptionMess(e));
                //logDebug.Warn(logDebug.except(e));
            }
        }

        private void insertList(string name, string value, string datatype)
        {
            int idx = G2_LV_parametricData.Items.Count + 1; // 数量自增
            ListViewItem li = new ListViewItem(idx.ToString()); // 实例对应列表项
            G2_LV_parametricData.Items.Add(li); // 添加对应项
            li.SubItems.AddRange(new string[] { "", name, "", datatype }); // 默认不初始化数值
        }

        /// <summary>
        /// 列表控件异常与显示
        /// </summary>
        /// <param name="b">bool</param>
        /// <param name="id">0 所有 1,4 文本框 2 数据类型下拉框 3 标题下拉框</param>
        private void initListCtrls(bool b, int id)
        {
            if (id == 1)
            {
                G2_TB_list_textbox.Visible = b;
            }
            else if (id == 2)
            {
                G2_CB_list_combobox.Visible = b;
            }
            else if (id == 3)
            {
                G2_CB_csvinfo_name.Visible = b;
            }
            else if (id == 4)
            {
                G2_TB_list_textbox.Visible = b;
            }
            else if (id == 0)
            {
                G2_TB_list_textbox.Visible = b;
                G2_CB_list_combobox.Visible = b;
                G2_CB_csvinfo_name.Visible = b;
            }
        }

        private void SortListView(ref ListView listView)
        {
            int idx = 1;
            foreach (ListViewItem item in listView.Items)
            {
                item.Text = idx.ToString();
                idx++;
            }
        }

        private string search_code(string keyword, bool isVCode)
        {
            if (isVCode)
            {
                m_sfcDcRequest.sfc = keyword;
                return csvinfo.getCcInVc(keyword);
            }
            else
            {
                if (csvinfo.getVcInCc(keyword) != "")
                {
                    return csvinfo.getVcInCc(keyword);
                }
                else // 有电芯码，无虚拟码，生成虚拟码
                {
                    DialogResult dr = MessageBox.Show(
                        "未搜索到 " + label_sfc.Text + "，是否进入设置？", "提示"
                        , MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    if (dr == DialogResult.OK)
                    {
                        m_VCode = "";
                        GenerateVC generateVCDlg = new GenerateVC(keyword);
                        generateVCDlg.ShowDialog();
                        return m_VCode;
                    }
                }
            }

            return ""; // 无电芯码，生成虚拟码失败
        }

        /// 线程加载
        public void setupLoadThread()
        {
            t_loadFile = new Thread(new ThreadStart(loadFile)); // 加载文件读取线程
            //t_loadFilebar = new Thread(new ThreadStart(setupProcessBar));
            t_loadFile.IsBackground = true;
            if (!isInLoadFile())
            {
                t_loadFile.Start();
                //t_loadFilebar.Start();
            }
        }

        #region csv 读取

        public void loadFile()
        {
            //INIConfigAPI.WriteFile(G1_TB_filepath.Text);
            lock (o)
            {
                csvinfo.loadFile(G1_TB_filepath.Text);
            }
        }

        public static bool isInLoadFile()
        {
            if (t_loadFile != null)
            {
                if (t_loadFile.IsAlive)
                {
                    //t_loadFile.Interrupt();
                    DialogResult dr = MessageBox.Show(
                               "加载文件中，确认取消？", "文件加载"
                               , MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                    try
                    {
                        if (dr == DialogResult.OK)
                        {
                            t_loadFile.Abort(); // 线程终止
                            return false;
                        }
                        else
                        {
                            //t_loadFile.Resume(); // 线程继续
                            return true;
                        }
                    }
                    catch (Exception e) // 线程异常
                    {
                        MessageBox.Show(Timing.exceptionMess(e));
                        errorLogger.Error(Timing.exceptionMess(e));

                        return true;
                    }
                    finally
                    {
                        t_loadFile = null;
                    }
                }
                else // 线程等待
                {

                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        #endregion

        public void saveMachineParamsSetInIni()
        {
            m_parametricDataArray = new List<machineIntegrationParametricData>();
            m_parametricDataArray.Clear();

            foreach (ListViewItem item in G2_LV_parametricData.Items)
            {
                machineIntegrationParametricData miParamtricData = new machineIntegrationParametricData();
                miParamtricData.name = item.SubItems[NAME].Text;
                miParamtricData.value = item.SubItems[VALUE].Text;
                switch (item.SubItems[DATATYPE].Text)
                {
                    case "NUMBER":
                        miParamtricData.dataType = ParameterDataType.NUMBER;
                        break;
                    case "TEXT":
                        miParamtricData.dataType = ParameterDataType.TEXT;
                        break;
                    case "FORMULA":
                        miParamtricData.dataType = ParameterDataType.FORMULA;
                        break;
                    case "BOOLEAN":
                        miParamtricData.dataType = ParameterDataType.BOOLEAN;
                        break;
                    default:
                        miParamtricData.dataType = ParameterDataType.TEXT;
                        break;
                }
                m_parametricDataArray.Add(miParamtricData); // 保存 DC 数据集
            }
            machineIntegrationParametricData[] paramData = m_parametricDataArray.ToArray();
            m_sfcDcRequest.parametricDataArray = paramData;

            m_nonConfirmCodeArray = new List<nonConfirmCodeArray>();
            nonConfirmCodeArray[] nonConfirmCodeArrays = m_nonConfirmCodeArray.ToArray();
            m_sfcDcRequest.ncCodeArray = nonConfirmCodeArrays;

            string paramtricDatajson = "{\"parametricDataArray\":[";

            int i = 0;
            foreach (var item in m_sfcDcRequest.parametricDataArray)
            {

                string itemJson = "{\"name\":\"" + item.name + "\", " +
                    "\"value\":\"" + item.value + "\" ," +
                     "\"dataType\":\"" + item.dataType.ToString() + "\""
                    + "} ";

                if (i != 0)
                {
                    paramtricDatajson = paramtricDatajson + "," + itemJson;
                }
                else
                {
                    paramtricDatajson += itemJson;
                }

                i++;
            }
            paramtricDatajson += "]}";

            string ncCodeArray = "";

            INIConfigAPI.commPath = iniPath;
            INIConfigAPI.WriteRequest(paramtricDatajson, ncCodeArray); // 保存 ini 
        }

        private void resetMain()
        {
            csvinfo.clear();

            t_isInLoadFile = false;

            t_loadFile = null;

        }

        public void writeFilePath(string path)
        {
            initListCtrls(false, 0);

            try // 路径可打开
            {
                if (!isInLoadFile())
                {
                    G1_BTN_searchSFC.Enabled = false;

                    if (File.Exists(path))
                    {
                        FileStream fs;
                        try
                        {
                            fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
                            fs.Close();

                            if (G2_CB_csvinfo_name.Items.Count > 0)
                            {
                                //G2_CB_csvinfo_name.DataSource = null;
                                //G2_CB_csvinfo_name.Items.Clear();

                                foreach (ListViewItem item in G2_LV_parametricData.Items) // 循环判断
                                {
                                    item.SubItems[TITLE].Text = "";
                                    item.SubItems[VALUE].Text = "";
                                }
                            }

                            G1_TB_filepath.Text = path;

                            resetMain();

                            setupLoadThread();

                            G1_BTN_searchSFC.Enabled = true;

                            G1_TB_sfc.Text = "";

                        }
                        catch (Exception e)
                        {
                            G1_TB_filepath.Text = "";
                            MessageBox.Show(Timing.exceptionMess(e));
                            errorLogger.Error(Timing.exceptionMess(e));
                        }
                    }
                    else
                    {
                        G1_TB_filepath.Text = "";
                    }
                }
                else // 线程等待
                {
                    //t_loadFile = null;
                }
            }
            catch (Exception e) // 文件加载异常
            {
                if (csvinfo.getCSV().Count >= 0)
                {
                    G1_BTN_searchSFC.Enabled = true;
                }

                MessageBox.Show(Timing.exceptionMess(e));
                errorLogger.Error(Timing.exceptionMess(e));
            }
        }

        private void G1_BTN_filepath_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.Filter = "表格文件(*.csv;*.xls;*.xlsx)|*.csv;*.xls;*.xlsx";
                //ofd.Filter = "表格文件(*.csv)|*.csv";
                ofd.ValidateNames = true; // 验证用户输入是否是一个有效的Windows文件名
                ofd.CheckFileExists = true; // 验证路径的有效性
                ofd.CheckPathExists = true;// 验证路径的有效性
                if (ofd.ShowDialog() == DialogResult.OK) // 用户点击确认按钮，发送确认消息
                {
                    writeFilePath(ofd.FileName);
                }
            }
        }

        private void G1_TB_filepath_TextChanged(object sender, EventArgs e)
        {
            writeFilePath(G1_TB_filepath.Text);
        }

        private void G1_BTN_searchSFC_Click(object sender, EventArgs e)
        {
            if (false)
            {
                MessageBox.Show("文件加载中...");
                return;
            }

            string temp = string.Empty;
            if (G1_TB_keyword.Text != "")
            {
                temp = search_code(G1_TB_keyword.Text, G1_CB_virtualcode.Checked);

                if (temp == "")
                {
                    G1_TB_sfc.Font = new Font("隶书", 9);
                    G1_TB_sfc.BackColor = Color.Red;

                    G1_TB_sfc.Text = "搜索失败，" + label_sfc.Text + "不存在";
                }
                else
                {
                    G1_TB_sfc.Font = new Font("宋体", 10);
                    G1_TB_sfc.BackColor = Color.GreenYellow;

                    G1_TB_sfc.Text = temp;
                    m_b_sfcIsNull = false;

                    titleUpdateValue(true);
                }
            }
            else
            {
                G1_TB_sfc.Font = new Font("隶书", 10);
                G1_TB_sfc.BackColor = Color.Gray;

                G1_TB_sfc.Text = "关键字无效，请确认输入";
            }
        }

        private void G2_BTN_insertData_Click(object sender, EventArgs e)
        {
            initListCtrls(false, 0);

            insertList("", "", "TEXT");
        }

        private void G2_LV_parametricData_MouseClick(object sender, MouseEventArgs e)
        {
            if (G2_LV_parametricData.SelectedItems.Count > 0) // 判断选中
            {
                m_listViewItem = G2_LV_parametricData.SelectedItems[0];

                int tl = m_listViewItem.SubItems[TITLE].Bounds.Left;
                int tr = m_listViewItem.SubItems[TITLE].Bounds.Right;
                int nl = m_listViewItem.SubItems[NAME].Bounds.Left;
                int nr = m_listViewItem.SubItems[NAME].Bounds.Right;
                int vl = m_listViewItem.SubItems[VALUE].Bounds.Left;
                int vr = m_listViewItem.SubItems[VALUE].Bounds.Right;
                int dl = m_listViewItem.SubItems[DATATYPE].Bounds.Left;
                int dr = m_listViewItem.SubItems[DATATYPE].Bounds.Right;

                if (e.X > tl && e.X < tr) // Name
                {
                    initListCtrls(true, 3); // 控件显示

                    m_listViewSubItem = m_listViewItem.GetSubItemAt(e.X, e.Y); // 显示指定单元格内容
                    if (m_listViewSubItem != null)
                    {
                        G2_CB_csvinfo_name.Text = m_listViewSubItem.Text;

                        G2_CB_csvinfo_name.Location = new Point(
                            m_listViewItem.SubItems[TITLE].Bounds.Location.X + G2_LV_parametricData.Bounds.Left,
                            m_listViewItem.SubItems[TITLE].Bounds.Location.Y + G2_LV_parametricData.Bounds.Top
                            ); // 控件位置大小
                        G2_CB_csvinfo_name.Width = m_listViewItem.GetSubItemAt(e.X, e.Y).Bounds.Width;

                        G2_CB_csvinfo_name.BringToFront(); // 控件置顶

                        if (t_loadFile != null && !t_loadFile.IsAlive && csvinfo.getPTList().Count() > 0)
                        {
                            G2_CB_csvinfo_name.DataSource = csvinfo.getPTList();
                        }
                    }
                }

                if (e.X > nl && e.X < vr) // 指定列表项：Value
                {
                    initListCtrls(true, 1); // 控件显示

                    m_listViewSubItem = m_listViewItem.GetSubItemAt(e.X, e.Y); // 显示指定单元格内容
                    if (m_listViewSubItem != null)
                    {
                        G2_TB_list_textbox.Text = m_listViewSubItem.Text;

                        G2_TB_list_textbox.Location = new Point(
                            m_listViewSubItem.Bounds.Location.X + G2_LV_parametricData.Bounds.Left,
                            m_listViewSubItem.Bounds.Location.Y + G2_LV_parametricData.Bounds.Top
                            ); // 控件位置大小
                        G2_TB_list_textbox.Width = m_listViewSubItem.Bounds.Width;

                        G2_TB_list_textbox.BringToFront(); // 控件置顶
                    }
                }

                if (e.X > dl && e.X < dr) // 指定列表项：DataType
                {
                    initListCtrls(true, 2); // 控件显示

                    m_listViewSubItem = m_listViewItem.GetSubItemAt(e.X, e.Y); // 显示指定单元格内容
                    if (m_listViewSubItem != null)
                    {
                        G2_CB_list_combobox.Text = m_listViewSubItem.Text;

                        G2_CB_list_combobox.Location = new Point(
                            m_listViewItem.SubItems[DATATYPE].Bounds.Location.X + G2_LV_parametricData.Bounds.Left,
                            m_listViewItem.SubItems[DATATYPE].Bounds.Location.Y + G2_LV_parametricData.Bounds.Top
                            ); // 控件位置大小
                        G2_CB_list_combobox.Width = m_listViewItem.GetSubItemAt(e.X, e.Y).Bounds.Width;

                        G2_CB_list_combobox.BringToFront(); // 控件置顶
                    }
                }
            }
        }

        private void G2_LV_parametricData_MouseDown(object sender, MouseEventArgs e)
        {
            if (G2_LV_parametricData.SelectedItems.Count != 0) // 默认隐藏
            {
                initListCtrls(false, 0);
            }
        }

        private void G2_BTN_removeData_Click(object sender, EventArgs e)
        {
            initListCtrls(false, 0);

            foreach (ListViewItem item in G2_LV_parametricData.Items)
            {
                if (item.Selected)
                {
                    item.Remove();
                }
            }

            SortListView(ref G2_LV_parametricData); // 移除中间项时需要进行排序

            if (G2_LV_parametricData.Items.Count != 0)
            {
                G2_LV_parametricData.Items[G2_LV_parametricData.Items.Count - 1].Selected
                    = true;
            }
        }

        private void G2_TB_list_textbox_TextChanged(object sender, EventArgs e)
        {
            if (m_listViewItem != null)
            {
                if (m_listViewSubItem != null)
                {
                    m_listViewSubItem.Text = G2_TB_list_textbox.Text;
                }
            }
        }

        private void G2_CB_list_combobox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (m_listViewItem != null)
            {
                m_listViewItem.SubItems[DATATYPE].Text = this.G2_CB_list_combobox.Text.ToString();
            }

            G2_CB_list_combobox.Visible = false;
        }

        private void M_G1_BTN_setWebservice_Click(object sender, EventArgs e)
        {
            try
            {
                string WSDL = M_G1_TB_wsdl.Text;
                string User = M_G1_TB_user.Text;
                string Password = M_G1_TB_password.Text;
                string TimeOut = M_G1_TB_timeout.Text;

                long temp2 = m_MachineConnRequest.SetConnectInfo(WSDL, User, Password, TimeOut);

                if (temp2 == CodeCollection.EXECUTE_SUCCESS)
                {
                    INIConfigAPI.commPath = iniPath;
                    bool temp = INIConfigAPI.WriteWebservice(WSDL, TimeOut, User
                        , EnDecryptAPI.EnCrypt(Password, pwdKey)); // 保存 ini

                    if (temp == true)
                    {
                        MessageBox.Show("webservice 服务设置成功！");
                    }
                    else
                    {
                        MessageBox.Show("webservice 服务设置成功，\r\n但保存 ini 失败，详情请看 MiFind 日志文档！");
                    }
                }
                else
                {
                    MessageBox.Show("webservice 服务设置失败，信息无效！");
                }

            }
            catch (Exception)
            {
                MessageBox.Show("webservice 服务设置失败，信息无效！");
                errorLogger.Error("webservice 服务设置失败，信息无效！");
            }
        }

        private void M_G2_BTN_setRequest_Click(object sender, EventArgs e)
        {
            try
            {
                m_sfcDcRequest.site = M_G2_TB_site.Text;
                m_sfcDcRequest.user = M_G2_TB_operationUser.Text;
                m_sfcDcRequest.operation = M_G2_TB_operation.Text;
                m_sfcDcRequest.operationRevision = M_G2_TB_operationRevision.Text;
                m_sfcDcRequest.activityId = M_G2_TB_activityID.Text;
                m_sfcDcRequest.resource = M_G2_TB_resource.Text;
                m_sfcDcRequest.dcGroup = M_G2_TB_dcGroup.Text;
                m_sfcDcRequest.dcGroupRevision = M_G2_TB_dcGroupRevision.Text;
                m_sfcDcRequest.sfc = G1_TB_sfc.Text;

                switch (M_G2_CB_modeProcessSFC.SelectedItem.ToString())
                {
                    case "COMPLETE_SFC":
                        m_sfcDcRequest.modeProcessSfc = ModeProcessSfc.MODE_COMPLETE_SFC_POST_DC;
                        break;
                    case "PASS_SFC":
                        m_sfcDcRequest.modeProcessSfc = ModeProcessSfc.MODE_PASS_SFC_POST_DC;
                        break;
                    case "START_SFC":
                        m_sfcDcRequest.modeProcessSfc = ModeProcessSfc.MODE_START_SFC_PRE_DC;
                        break;
                    case "START_COMPLETE_SFC":
                        m_sfcDcRequest.modeProcessSfc = ModeProcessSfc.MODE_REMOVE_PROCESSLOT_COMPLETE_SFC_POST_DC;
                        break;
                    case "NONE":
                    default:
                        m_sfcDcRequest.modeProcessSfc = ModeProcessSfc.MODE_NONE;
                        break;
                }

                INIConfigAPI.commPath = iniPath;
                bool temp = INIConfigAPI.WriteRequest(true, m_sfcDcRequest.site, m_sfcDcRequest.user
                    , m_sfcDcRequest.operation, m_sfcDcRequest.operationRevision
                    , m_sfcDcRequest.activityId, m_sfcDcRequest.resource
                    , M_G2_CB_modeProcessSFC.SelectedItem.ToString(), m_sfcDcRequest.dcGroup
                    , m_sfcDcRequest.dcGroupRevision);  // 保存 ini

                if (temp)
                {
                    MessageBox.Show("request 请求设置成功！");
                }
                else
                {
                    MessageBox.Show("request 请求设置成功，\r\n但保存 ini 失败，详情请看 MiFind 日志文档！");
                }

            }
            catch (Exception)
            {
                MessageBox.Show("request 请求设置失败，信息无效！");
                errorLogger.Error("request 请求设置失败，信息无效！");
                throw;
            }

        }

        private void G1_TB_sfc_TextChanged(object sender, EventArgs e)
        {
            if (G1_TB_sfc.Text != "")
            {
                m_b_sfcIsNull = false;
            }
            else
            {
                m_b_sfcIsNull = true;
            }

            if (m_b_sfcIsNull)
            {
                G3_BTN_RUpload.Enabled = false;
            }
            else
            {
                G3_BTN_RUpload.Enabled = true;
            }
        }

        private void G3_BTN_RUpload_Click(object sender, EventArgs e)
        {
            m_sfcDcRequest.sfc = G1_TB_sfc.Text;

            saveMachineParamsSetInIni();

            string sfc = G1_TB_sfc.Text;
            if (G1_CB_virtualcode.Checked)
            {
                sfc = G1_TB_keyword.Text;
            }

            m_MachineConnRequest.SetupResponse(m_sfcDcRequest, out code, out message); // 上传响应

            int idx = G3_LV_responserecord.Items.Count + 1; // 数量自增
            ListViewItem li = new ListViewItem(idx.ToString()); // 实例对应列表项
            G3_LV_responserecord.Items.Add(li); // 添加对应项

            string yes = "✔";
            string no = "✘";
            string codedes = code == 0 ? yes : no;
            li.SubItems.AddRange(new string[] { sfc, codedes, message });

            if (codedes == yes)
            {
                G3_LV_responserecord.Items[G3_LV_responserecord.Items.Count - 1].ForeColor = Color.GreenYellow;
            }
            else
            {
                G3_LV_responserecord.Items[G3_LV_responserecord.Items.Count - 1].ForeColor = Color.Red;
            }

            G3_LV_responserecord.Items[G3_LV_responserecord.Items.Count - 1].SubItems[2].Font
            = new Font("宋体", 8, FontStyle.Bold);
            G3_LV_responserecord.Items[G3_LV_responserecord.Items.Count - 1].SubItems[2].BackColor
                = Color.White;

            G3_LV_responserecord.Items[G3_LV_responserecord.Items.Count - 1].Selected = true;

            G3_RTB_response.Font = new Font("宋体", 14, FontStyle.Regular);
            G3_RTB_response.Text = "sfc:" + sfc + "\r\n结果: " + (code == 0 ? "事务执行正常" : "事务执行异常")
                + "\r\n描述: " + message;
        }

        private void G1_BTN_generate_Click(object sender, EventArgs e)
        {
            GenerateVC generateVCDlg = new GenerateVC("");
            generateVCDlg.ShowDialog();
        }

        private void G1_CB_virtualcode_CheckedChanged(object sender, EventArgs e)
        {
            if (G1_CB_virtualcode.Checked)
            {
                label_sfc.Text = "电芯码";
                label_sfc.ForeColor = Color.BlueViolet;
            }
            else
            {
                label_sfc.Text = "sfc";
                label_sfc.Font = new Font("隶书", 9, FontStyle.Bold);
                label_sfc.ForeColor = Color.Black;
            }
        }

        private void G2_BTN_listset_Click(object sender, EventArgs e)
        {
            saveMachineParamsSetInIni();
        }

        private void G3_LV_responserecord_SelectedIndexChanged(object sender, EventArgs e)
        {
            G3_LV_responserecord.Items[G3_LV_responserecord.Items.Count - 1].EnsureVisible();
        }

        private void G3_LV_responserecord_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo info = G3_LV_responserecord.HitTest(e.X, e.Y);
            if (info.Item != null)
            {
                string des = "       序号：" + info.Item.SubItems[0].Text
                    + "\r\n         sfc：" + info.Item.SubItems[1].Text
                    + "\r\n执行结果：" + info.Item.SubItems[2].Text
                    + "\r\n       描述：" + info.Item.SubItems[3].Text;
                MessageBox.Show(des);
            }
        }

        private void G2_LV_parametricData_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            ListViewHitTestInfo info = G2_LV_parametricData.HitTest(e.X, e.Y);
            if (info.Item != null)
            {
                string des = "       序号：" + info.Item.SubItems[0].Text
                    + "\r\n表头标题：" + info.Item.SubItems[TITLE].Text
                    + "\r\n参数名称：" + info.Item.SubItems[NAME].Text
                    + "\r\n数据类型：" + info.Item.SubItems[DATATYPE].Text
                    + "\r\n    参数值：" + info.Item.SubItems[VALUE].Text;
                MessageBox.Show(des);
            }
        }

        private void M_G1_PB_closeOpen_MouseClick(object sender, MouseEventArgs e)
        {
            M_G1_PB_closeOpen.SizeMode = PictureBoxSizeMode.Zoom;

            Image image1 = mesRUpload.Properties.Resources.close;

            if (m_b_isOpen)
            {
                image1 = mesRUpload.Properties.Resources.open;
                M_G1_TB_password.PasswordChar = new char();
                m_b_isOpen = false;
            }
            else
            {
                M_G1_TB_password.PasswordChar = '●';
                m_b_isOpen = true;
            }

            M_G1_PB_closeOpen.Image = image1;
        }

        private void G2_TB_list_textbox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                G2_TB_list_textbox.Visible = false;
            }
        }

        private void titleUpdateValue(bool isupdate, string title = "")
        {
            csvinfo.setCurrentLine(G1_TB_keyword.Text // 设置对应行
                , G1_CB_virtualcode.Checked);

            string name = string.Empty;
            int i = 0;
            foreach (ListViewItem item in G2_LV_parametricData.Items) // 循环判断
            {
                if (!isupdate)
                {
                    name = title;
                }
                else
                {
                    if (item.SubItems[TITLE].Text == "") // 列表有值
                    {
                        item.SubItems[VALUE].Text = "";
                        continue;
                    }
                    name = item.SubItems[TITLE].Text;

                    G2_LV_parametricData.Items[i].Selected = true;
                    m_listViewItem = G2_LV_parametricData.SelectedItems[0];
                }

                if (csvinfo.getCSV().Count > 0)
                {
                    int sel = csvinfo.getPTList().IndexOf(name); // 获取对应列
                    List<List<string>> temp = csvinfo.getCSV();
                    if (csvinfo.currentLine != -1
                        && csvinfo.currentLine != CodeCollection.DATA_ISNOTEXIST
                        && temp[csvinfo.currentLine].Count >= sel)
                    {
                        List<string> temp2 = new List<string>(
                            temp[csvinfo.currentLine]);
                        m_listViewItem.SubItems[VALUE].Text = temp2[sel];
                        label_list_value_isexist.Text = "";
                    }
                    else if (csvinfo.currentLine == -1)
                    {
                        label_list_value_isexist.Text
                            = "" + m_listViewItem.SubItems[1].Text
                            + " 无对应 value，请输入！";
                        label_list_value_isexist.Font
                            = new Font("隶书", 9, FontStyle.Bold);
                        label_list_value_isexist.ForeColor = Color.Red;

                        m_listViewItem.SubItems[VALUE].Text = "";
                    }
                    else
                    {
                        m_listViewItem.SubItems[VALUE].Text = "";
                    }

                    if (!isupdate)
                    {
                        break;
                    }
                    else
                    {
                        G2_LV_parametricData.Items[i].Selected = false;
                        i++;
                    }
                }
            }
        }

        private void G2_CB_csvinfo_name_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (m_listViewItem != null)
            {
                m_listViewItem.SubItems[TITLE].Text
                    = this.G2_CB_csvinfo_name.Text.ToString(); // 标题
                string selectstr = m_listViewItem.SubItems[TITLE].Text;

                if (t_loadFile != null && !t_loadFile.IsAlive
                    && csvinfo.getPTList().Count() > 0)
                {
                    if (G1_TB_keyword.Text != "")
                    {
                        titleUpdateValue(false, selectstr);
                    }
                }
            }

            G2_CB_csvinfo_name.Visible = false;
        }

        private void G2_CB_csvinfo_name_Leave(object sender, EventArgs e)
        {
            G2_CB_csvinfo_name.Visible = false;
        }

        private void MESUpload_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult.OK == MessageBox.Show("请确认参数是否设置完成！是否关闭窗口？",
                "警告",
                MessageBoxButtons.OKCancel,
                MessageBoxIcon.Warning))
            {
                if (csvinfo != null)
                {
                    csvinfo.clear();
                    csvinfo = null;
                }

                if (t_loadFile != null)
                {
                    if (t_loadFile.IsAlive)
                    {
                        t_loadFile.Abort();
                        t_loadFile = null;
                    }
                    t_isInLoadFile = false;
                }

                e.Cancel = false;

                NoticeProgressBar.close_circle_dialog();

                //Application.Exit(); // 阻断所有线程
                Application.ExitThread();
                //System.Environment.Exit(0);
            }
            else
            {
                e.Cancel = true;
            }
        }
    }
}
